package com.unicom.priceboard.data.hose;

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import com.unicom.priceboard.data.vo.MarketStatus;
import com.unicom.priceboard.thread.MarketStatusThread;
import com.unicom.priceboard.util.Util;

public class MarketStatusReader {
	private static final Logger logger = Logger.getLogger(MarketStatusReader.class);
	public void MarketReader(String path){
		try{
			FileInputStream instrMarketStat = new FileInputStream(Util.getCurrentDataPath(path));
			readDATFile(instrMarketStat);
			instrMarketStat.close();
		}catch(Exception e){
		//write file log
			logger.debug("*****parsing Security process error :\n"+e.getMessage());
		}
	}
	private void readDATFile(InputStream is)
	{
		List<com.unicom.priceboard.data.vo.MarketStatus> lstMarketStats = new ArrayList<MarketStatus>();
		DataInputStream input = new DataInputStream(is);		
		try{
//			if(input.available()>10)
//				input.skipBytes(input.available()-10);// get 2 record from the end
			while(input.available()>0)
			{
				com.unicom.priceboard.data.vo.MarketStatus marketStatus = new MarketStatus();
				
				//Create a new ByteBuffer to store a record from file
				ByteBuffer buf = ByteBuffer.allocate(5);
				//Set to little endian
				buf.order(ByteOrder.LITTLE_ENDIAN);
				//Get each field from the file and put it to the byte buffer
				buf.put(input.readByte());//ControlCode
				buf.putInt(input.readInt());//Time
				
				//Reset position for reading
				buf.flip();
				// Set to big endian
				buf.order(ByteOrder.BIG_ENDIAN);
				
				//Retrieve data from byte buffer
				marketStatus.setControlCode((char)buf.get());
				marketStatus.setTime(buf.getInt());				
				lstMarketStats.add(marketStatus);
			}			
			//get the previous State of Market
			if(lstMarketStats.size()>1)
				MarketStatusThread.prevStat = lstMarketStats.get(lstMarketStats.size()-2).getControlCode();			
			//get the current state of Market (last element of the list)
			MarketStatusThread.curStat = lstMarketStats.get(lstMarketStats.size()-1).getControlCode();
			input.close();
		}catch(Exception ex)
		{
			logger.info("End of file: " + ex);
		}		
	}
}
